package com.lw.leetcode.other.c;

import java.util.*;

/**
 * Created with IntelliJ IDEA.
 * 381. O(1) 时间插入、删除和获取随机元素 - 允许重复
 *
 * @author liw
 * @version 1.0
 * @date 2023/2/13 16:58
 */
public class RandomizedCollection {

    public static void main(String[] args) {
        RandomizedCollection test = new RandomizedCollection();

        System.out.println(test.insert(1));
        System.out.println(test.remove(1));
        System.out.println(test.insert(1));

    }

    private Map<Integer, Set<Integer>> map = new HashMap<>();
    private List<Integer> list = new ArrayList<>();

    public RandomizedCollection() {

    }

    public boolean insert(int val) {
        Set<Integer> li = map.getOrDefault(val, new HashSet<>());
        boolean f = li.isEmpty();
        this.list.add(val);
        li.add(list.size() - 1);
        map.put(val, li);
        return f;
    }

    public boolean remove(int val) {
        Set<Integer> li = map.get(val);
        if (li == null || li.isEmpty()) {
            return false;
        }
        if (list.get(list.size() - 1) == val) {
            map.get(val).remove(list.size() - 1);
            list.remove(list.size() - 1);
            return true;
        }
        int index = li.stream().findFirst().get();
        li.remove(index);
        int lastValue = list.get(list.size() - 1);
        Set<Integer> lastList = map.get(lastValue);
        lastList.remove(list.size() - 1);
        lastList.add(index);
        list.set(index, lastValue);
        list.remove(list.size() - 1);
        return true;
    }

    public int getRandom() {
        return list.get((int) (list.size() * Math.random()));
    }

}
